package com.tengju.bff.interfaces.covercharge.util.alarmUtil;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.idanchuang.component.base.JsonResult;
import com.idanchuang.component.base.exception.common.ErrorCode;
import com.idanchuang.component.config.apollo.util.ConfigUtil;
import com.tengju.bff.interfaces.shared.ApiResponse;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.*;

/**
 * 钉钉相关工具类
 */
@Slf4j
public class DingUtils {

    /**
     * 钉钉群组消息通知
     *
     * @param content    消息内容
     * @param mobileList 需要@的人的手机号，不@就传空
     * @return
     */
    public static ApiResponse<?> groupNotice(String content, List<String> mobileList) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("msgtype", "text");

            Map<String, Object> textMap = new HashMap<>();
            textMap.put("content", content);
            map.put("text", textMap);

            if (CollectionUtil.isNotEmpty(mobileList)) {
                Map<String, Object> atMap = new HashMap<>();
                String[] mobileArray = mobileList.toArray(new String[mobileList.size()]);
                atMap.put("atMobiles", mobileArray);
                map.put("at", atMap);
            }

            String secret = ConfigUtil.getConfig().getString("dinggroup.secret", "SEC3c89f0071bc43e9d223599e20f6df6fdfcd4d80fe5e77d88333bb5c00c514964");
            String url = ConfigUtil.getConfig().getString("dinggroup.url", "https://oapi.dingtalk.com/robot/send?access_token=afe14f04542545513d2f66b1976f7348834313c75a18d6a07e16ea8021f852b8");
            long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + secret;

            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));

            String sign = URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), "UTF-8");
            String result = HttpUtil.post(url + "&timestamp=" + timestamp + "&sign=" + sign, JSON.toJSONString(map));
            Map<String, Object> resultMap = JSON.parseObject(result, Map.class);
            if ((Integer) resultMap.get("errcode") == 0) {
                return ApiResponse.newSuccess();
            } else {
                return ApiResponse.newFailure((Integer) resultMap.get("errcode"), (String) resultMap.get("errmsg"));
            }
        } catch (Exception e) {
            log.error("钉钉群组消息通知异常",e);
            return ApiResponse.newFailure(ErrorCode.SYSTEM_ERROR.getCode(), e.getMessage());
        }

    }

    public static void main(String[] args) {
        List<String> mobileList = new ArrayList<>();
        mobileList.add("13717929664");
        ApiResponse<?> jsonResult = groupNotice("机器人test...", mobileList);
        System.out.println(jsonResult);
    }

}
